<template>
  <div class="el_main_con">
    <Breadcrumb></Breadcrumb>
    <el-card>
      <el-alert show-icon title="添加商品信息" center type="info" :closable="false">
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex-0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab区域 -->
      <el-form :model="addForm" ref="addForm" :rules="addFormRules" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTableave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="categoriesList" :props="catecadeProps" @change="parentCateChanged()"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in getCatAttributesManyList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in getCatAttributesOnlyList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" list-type="picture" :headers="header">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button size="small" type="primary" class="addbtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="preViewVisible" width="30%">
      <img :src="preViewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import { Goods, Categories } from '@/api/apiConfig'
import Breadcrumb from 'components/breadcrumb/breadcrumb'
export default {
  components: {
    Breadcrumb
  },
  data () {
    return {
      activeIndex: '0',
      addForm: {
        // 商品名称不能为空
        goods_name: '',
        // 以','分割的分类列表不能为空
        goods_cat: [],
        // 价格不能为空
        goods_price: 0,
        // 数量不能为空
        goods_number: 0,
        // 重量不能为空
        goods_weight: 0,
        // 介绍
        goods_introduce: '',
        // 可以为空上传的图片临时路径（对象）
        pics: [],
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      categoriesList: [],
      catecadeProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      cat_pid: '',
      getCatAttributesManyList: [],
      getCatAttributesOnlyList: [],
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      header: {
        Authorization: this.$jsCookie.get('token')
      },
      preViewVisible: false,
      preViewPath: ''
    }
  },
  mounted () {
    this.getCategories()
  },
  methods: {
    getCategories () {
      const params = {}
      Categories.getCategories(params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.categoriesList = res.data
      })
    },
    parentCateChanged () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
      if (this.addForm.goods_cat.length > 0) {
        this.cat_pid = this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
      }
    },
    beforeTableave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    tabClick () {
      const url = `categories/${this.cat_pid}/attributes`
      const params = {
        sel: 'many'
      }
      if (this.activeIndex === '1') {
        Categories.getCatAttributes(url, params).then(res => {
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          })
          this.getCatAttributesManyList = res.data
        })
      } else if (this.activeIndex === '2') {
        params.sel = 'only'
        Categories.getCatAttributes(url, params).then(res => {
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.getCatAttributesOnlyList = res.data
        })
      }
    },
    handlePreview (file) {
      this.preViewVisible = true
      this.preViewPath = file.response.data.url
    },
    handleRemove (file) {
      const filePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      this.addForm.pics.splice(i, 1)
    },
    handleSuccess (response) {
      if (response.meta.status !== 200) return this.$message.error(response.meta.msg)
      this.$message.success(response.meta.msg)
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(picInfo)
    },
    addGoods () {
      this.$refs.addForm.validate((valid) => {
        if (!valid) {
          this.$message.error('请填写必要的表单项')
          return false
        }
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        this.getCatAttributesManyList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        this.getCatAttributesOnlyList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        Goods.addGoods(form).then(res => {
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message({
            message: res.meta.msg,
            type: 'success',
            onClose: () => {
              this.$router.push({
                path: '/goods'
              })
              this.addForm = {
                // 商品名称不能为空
                goods_name: '',
                // 以','分割的分类列表不能为空
                goods_cat: [],
                // 价格不能为空
                goods_price: 0,
                // 数量不能为空
                goods_number: 0,
                // 重量不能为空
                goods_weight: 0,
                // 介绍
                goods_introduce: '',
                // 可以为空上传的图片临时路径（对象）
                pics: [],
                // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
                attrs: []
              }
            }
          })
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.previewImg {
  width: 100%;
}
.addbtn {
  margin: 15px 0;
}
</style>
